package com.redxiii.spike.pmi.command;

import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redxiii.spike.api.command.CommandFactory;
import com.redxiii.spike.api.command.InitializationRequired;
import com.redxiii.spike.api.pmi.entity.Issue;
import com.redxiii.spike.util.message.BasicMsgInterpreter;

/**
 * @author Daniel Filgueiras
 * 17/11/2011
 */
@InitializationRequired
@CommandFactory(BasicMsgInterpreter.class)
public class ActiveIssues extends ShowIssues {

	private static final Logger logger = LoggerFactory.getLogger(ActiveIssues.class);
	
	private static Comparator<Issue> recentOrder = new Comparator<Issue>() {
		@Override
		public int compare(Issue o1, Issue o2) {
			
			if (o1.getUpdatedOn() == null || o2.getUpdatedOn() == null)
				return o1.compareTo(o2);
			
			int resp = o2.getUpdatedOn().compareTo(o1.getUpdatedOn());
			if (resp == 0)
				return o1.compareTo(o2);
			
			return resp;
		}
	};
	
	@Override
	protected SortedSet<Issue> fetchIssues(String memberId) {
		
		SortedSet<Issue> issues = new TreeSet<Issue>(recentOrder);  
		
		issues.addAll(database.getMyActiveIssues(memberId));
		
		logger.debug("Found {} issues", issues.size());
		
		return issues;
	}
	
	@Override
	protected void buildResponse(Issue issue, StringBuilder buffer) {
		buffer
			.append("#")
			.append(Long.toString(issue.getId()))
			.append(" - ")
			.append(issue.getAssignedMember() != null ? issue.getAssignedMember().getName() : "unknown")
			.append(" - ")
			.append(issue.getSummary())
			.append("\r\n");
	}
}
